// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ReflectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.entity.StockInFinishedProduct;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.inventory.model.InventoryStorageVo;
import com.fowo.api.inventory.model.SimpleInventoryItem;
import com.fowo.api.inventory.model.TargetTypeEnum;
import com.fowo.api.inventory.model.form.InventoryStorageFormVo;
import com.fowo.api.inventory.service.InventoryBusinessService;
import com.fowo.api.mapper.StockInFinishedProductMapper;
import com.fowo.api.mapper.StockInProductMapper;
import com.fowo.api.model.stock.in.finished.product.StockInFinishedProductBatchPushPyAction;
import com.fowo.api.model.stock.in.finished.product.StockInFinishedProductItemVo;
import com.fowo.api.model.stock.in.finished.product.StockInFinishedProductPrintFNSKUBarcodeCustomsAction;
import com.fowo.api.model.stock.in.finished.product.StockInFinishedProductPrintFNSKUBarcodeTemplatesAction;
import com.fowo.api.model.stock.in.finished.product.StockInFinishedProductPrintProductBarCodeCustomsAction;
import com.fowo.api.model.stock.in.finished.product.StockInFinishedProductPrintProductBarCodeTemplatesAction;
import com.fowo.api.model.stock.in.finished.product.StockInFinishedProductPrintReceiptTemplatesAction;
import com.fowo.api.model.stock.in.finished.product.StockInFinishedProductPushLingXingAction;
import com.fowo.api.model.stock.in.finished.product.StockInFinishedProductPushPayableAction;
import com.fowo.api.model.stock.in.finished.product.StockInFinishedProductPushSellOrderAction;
import com.fowo.api.model.stock.in.finished.product.StockInFinishedProductPushStockOtherAction;
import com.fowo.api.model.stock.in.finished.product.StockInFinishedProductSearchParamPo;
import com.fowo.api.model.stock.in.finished.product.StockInFinishedProductSyncWarehousingOrderAction;
import com.fowo.api.model.stock.in.finished.product.StockInFinishedProductVo;
import com.fowo.api.model.stock.in.product.StockInProductItemVo;
import com.fowo.api.model.stock.in.product.StockInProductItemVoPages;
import com.fowo.api.model.stock.in.product.StockInProductSearchParamPo;
import com.fowo.api.service.StockInFinishedProductService;
import com.fowo.api.service.StockInProductService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.component.ExecuteScriptEngine;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.model.NewSerialRequest;
import com.fowo.api.sys.service.SysSerialService;
import com.fowo.api.user.model.JwtUserInfo;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 成品入库单 服务实现基类
 * @author 蜂窝蜜造平台 配置人：鹿丙涛，郑天琪
 */
@Slf4j
@DataObjectType(StockInFinishedProduct.class)
@DS("ds24")
public class StockInFinishedProductBaseServiceImpl
  extends ServiceImpl<StockInFinishedProductMapper, StockInFinishedProduct>
  implements StockInFinishedProductService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("warehouseName", "w.`name`");
      put("supplierSupplierName", "s.`supplier_name`");
      put("applicationDepName", "sd.`name`");
      put("cgUidName", "su.`name`");
      put("purchasingOrgName", "do.`name`");
      put("needOrgName", "do2.`name`");
    }
  };

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected StockInFinishedProductService self;

  @Resource
  protected StockInProductService stockInProductService;

  @Resource
  protected SysSerialService sysSerialService;

  @Resource
  protected WorkFlowService workFlowService;

  @Autowired(required = false)
  protected StockInFinishedProductPushLingXingAction stockInFinishedProductPushLingXingAction;

  @Autowired(required = false)
  protected StockInFinishedProductPrintReceiptTemplatesAction stockInFinishedProductPrintReceiptTemplatesAction;

  @Autowired(required = false)
  protected StockInFinishedProductPrintProductBarCodeCustomsAction stockInFinishedProductPrintProductBarCodeCustomsAction;

  @Autowired(required = false)
  protected StockInFinishedProductPrintProductBarCodeTemplatesAction stockInFinishedProductPrintProductBarCodeTemplatesAction;

  @Autowired(required = false)
  protected StockInFinishedProductPrintFNSKUBarcodeCustomsAction stockInFinishedProductPrintFNSKUBarcodeCustomsAction;

  @Autowired(required = false)
  protected StockInFinishedProductPrintFNSKUBarcodeTemplatesAction stockInFinishedProductPrintFNSKUBarcodeTemplatesAction;

  @Resource
  private ExecuteScriptEngine executeScriptEngine;

  @Resource
  protected InventoryBusinessService inventoryBusinessService;

  @Autowired(required = false)
  protected StockInFinishedProductBatchPushPyAction stockInFinishedProductBatchPushPyAction;

  @Autowired(required = false)
  protected StockInFinishedProductPushStockOtherAction stockInFinishedProductPushStockOtherAction;

  @Autowired(required = false)
  protected StockInFinishedProductPushSellOrderAction stockInFinishedProductPushSellOrderAction;

  @Autowired(required = false)
  protected StockInFinishedProductSyncWarehousingOrderAction stockInFinishedProductSyncWarehousingOrderAction;

  @Autowired(required = false)
  protected StockInFinishedProductPushPayableAction stockInFinishedProductPushPayableAction;

  @Resource
  protected Validator validator;

  /**
   * 创建成品入库单
   * @param model 成品入库单
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(StockInFinishedProductVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    StockInFinishedProduct entity = new StockInFinishedProduct();
    BeanUtils.copyProperties(model, entity);
    // 设置常量字段
    entity.setProductType("1");
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }

    if (model.getReceiptType() == null) {
      entity.setReceiptType("RK002");
    }

    if (model.getCostAllocationType() == null) {
      entity.setCostAllocationType("1");
    }

    if (model.getProductType() == null) {
      entity.setProductType("1");
    }

    if (model.getGenerateAp() == null) {
      entity.setGenerateAp("0");
    }

    if (model.getAStatus() == null) {
      entity.setAStatus("committed");
    }

    if (model.getStatus() == null) {
      entity.setStatus("2");
    }

    if (model.getIsPush() == null) {
      entity.setIsPush(false);
    }

    if (model.getAddType() == null) {
      entity.setAddType("1");
    }
    // 填充序列号
    if (!StringUtils.hasText(entity.getOrderSn())) {
      entity.setOrderSn(
        sysSerialService.getNewSerial(
          new NewSerialRequest(null, "StockInFinishedProduct.orderSn")
        )
      );
    }
    if (this.save(entity)) {
      model.setId(entity.getId());
      updateAllChilds(model);
      baseMapper.updateCalcFields(entity.getId());
      return entity.getId();
    }
    throw new Exception("成品入库单保存失败");
  }

  /**
   * 更新所有子表
   * @param model 成品入库单
   */
  protected void updateAllChilds(StockInFinishedProductVo model)
    throws Exception {
    if (model.getProductList() != null) {
      stockInProductService.saveAllByParentStockInId(
        model.getId(),
        model.getProductList()
      );
    }
  }

  /**
   * 更新成品入库单
   * @param model 成品入库单
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(StockInFinishedProductVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    StockInFinishedProduct entity = this.getById(model.getId());
    if (entity == null || !Objects.equals(entity.getProductType(), "1")) {
      throw new Exception("成品入库单不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "createTime",
      "createUser",
      "lastUpdateTime",
      "lastUpdateUser",
      "totalAmount",
      "totalNum"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      updateAllChilds(model);
      baseMapper.updateCalcFields(entity.getId());
      return true;
    }
    return false;
  }/**
   * 更新成品入库单（带空值）
   * @param model 成品入库单
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(StockInFinishedProductVo model)
    throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    StockInFinishedProduct entity = this.getById(model.getId());
    if (entity == null || !Objects.equals(entity.getProductType(), "1")) {
      throw new Exception("成品入库单不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(StockInFinishedProduct::getLastUpdateTime, model.getLastUpdateTime())
      .set(StockInFinishedProduct::getLastUpdateUser, model.getLastUpdateUser())
      .set(StockInFinishedProduct::getWarehouse, model.getWarehouse())
      .set(StockInFinishedProduct::getReceiptType, model.getReceiptType())
      .set(StockInFinishedProduct::getTotalStorage, model.getTotalStorage())
      .set(StockInFinishedProduct::getAssociatedPo, model.getAssociatedPo())
      .set(StockInFinishedProduct::getRemarks, model.getRemarks())
      .set(StockInFinishedProduct::getSupplier, model.getSupplier())
      .set(StockInFinishedProduct::getFreight, model.getFreight())
      .set(StockInFinishedProduct::getOtherExpenses, model.getOtherExpenses())
      .set(
        StockInFinishedProduct::getCostAllocationType,
        model.getCostAllocationType()
      )
      .set(
        StockInFinishedProduct::getWarehousingDate,
        model.getWarehousingDate()
      )
      .set(StockInFinishedProduct::getApplicationDep, model.getApplicationDep())
      .set(StockInFinishedProduct::getProductType, model.getProductType())
      .set(
        StockInFinishedProduct::getApplicationDepName1,
        model.getApplicationDepName1()
      )
      .set(StockInFinishedProduct::getWid, model.getWid())
      .set(StockInFinishedProduct::getCgUid, model.getCgUid())
      .set(StockInFinishedProduct::getPurchasingOrg, model.getPurchasingOrg())
      .set(StockInFinishedProduct::getNeedOrg, model.getNeedOrg())
      .set(StockInFinishedProduct::getRejectRemark, model.getRejectRemark())
      .set(
        model.getEnclosure() != null,
        StockInFinishedProduct::getEnclosure,
        JSON.toJSONString(model.getEnclosure())
      )
      .setSql(model.getEnclosure() == null, "enclosure = null")
      .set(StockInFinishedProduct::getAStatus, model.getAStatus())
      .set(
        StockInFinishedProduct::getPurchaseOrderCode,
        model.getPurchaseOrderCode()
      )
      .set(StockInFinishedProduct::getParentId, model.getParentId())
      .set(StockInFinishedProduct::getIsPush, model.getIsPush())
      .set(StockInFinishedProduct::getRevocation, model.getRevocation())
      .eq(StockInFinishedProduct::getId, model.getId())
      .update();
    if (isOk) {
      updateAllChilds(model);
      baseMapper.updateCalcFields(model.getId());
    }
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(
    StockInFinishedProductSearchParamPo search
  ) {
    return false;
  }

  /**
   * 批量删除指定主键列表关联的所有子表数据(此方法不包括事务，必须由其它已包括事务的方法调用)
   */
  protected void batchDeleteChilds(List<Long> ids) throws Exception {
    // 处理子表字段 商品列表(productList) 对应的对象
    StockInProductSearchParamPo productListSearchParam =
      new StockInProductSearchParamPo();
    productListSearchParam.setDisableDataPremissions(true);
    productListSearchParam.setParentStockInIdInList(ids);
    StockInProductMapper localStockInProductMapper = ContextHolder
      .getApplicationContext()
      .getBean(StockInProductMapper.class);
    productListSearchParam.applySqlSegments();
    List<Long> productListIdList = localStockInProductMapper.searchIds(
      productListSearchParam
    );
    if (!productListIdList.isEmpty()) {
      StockInProductService localStockInProductService = ContextHolder
        .getApplicationContext()
        .getBean(StockInProductService.class);
      localStockInProductService.batchDelete(productListIdList);
    }
  }

  /**
   * 删除成品入库单
   * @param id 成品入库单的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    batchDeleteChilds(Collections.singletonList(id));
    return this.removeById(id);
  }

  /**
   * 批量删除成品入库单
   * @param ids 成品入库单的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    batchDeleteChilds(ids);

    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 通过采购员查询成品入库单主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByCgRealname(String cgRealname) {
    return this.baseMapper.getIdByCgRealname(cgRealname);
  }

  /**
   * 通过采购员查询成品入库单多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByCgRealname(List<String> list) {
    return this.baseMapper.getIdsByCgRealname(list);
  }

  /**
   * 通过成品入库单主键查询采购员
   */
  @Override
  public String getCgRealnameById(Long id) {
    return this.baseMapper.getCgRealnameById(id);
  }

  /**
   * 通过成品入库单主键查询采购员列表
   */
  @Override
  public List<String> getCgRealnameByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getCgRealnameByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("cgRealname"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 成品入库单的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public StockInFinishedProductVo getVoById(Long id) throws Exception {
    StockInFinishedProductVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }

    StockInProductSearchParamPo productListSearchParamPo =
      new StockInProductSearchParamPo();
    productListSearchParamPo.setParentStockInId(id);
    productListSearchParamPo.getExtendData().put("queryMode", "sub");
    productListSearchParamPo
      .getExtendData()
      .put("queryParent", "StockInFinishedProduct");
    productListSearchParamPo.applySqlSegments();
    vo.setProductList(stockInProductService.search(productListSearchParamPo));

    return vo;
  }

  /**
   * 分页查询成品入库单
   * @param search 查询条件
   * @return 成品入库单分页查询结果
   */
  @Override
  public Page<StockInFinishedProductItemVo> pageSearch(
    StockInFinishedProductSearchParamPo search
  ) {
    Page<StockInFinishedProductItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(StockInFinishedProductItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 通用方法，为列表添加子表数据
   * @param pageResult 列表结果
   */
  protected Page<?> appendWithChild(
    Page<StockInFinishedProductItemVo> pageResult
  ) {
    return appendWithChild(pageResult, null);
  }

  /**
   * 通用方法，为列表添加子表数据
   * @param pageResult 列表结果
   * @param sort 子表排序
   */
  protected Page<?> appendWithChild(
    Page<StockInFinishedProductItemVo> pageResult,
    String sort
  ) {
    if (
      pageResult == null ||
      pageResult.getRecords() == null ||
      pageResult.getRecords().isEmpty()
    ) {
      return pageResult;
    }
    Page<JSONObject> withChildPage = new Page<>(
      pageResult.getCurrent(),
      pageResult.getSize(),
      pageResult.getTotal()
    );
    withChildPage.setRecords(new ArrayList<>());

    StockInProductSearchParamPo productListSearchParamPo =
      new StockInProductSearchParamPo();
    productListSearchParamPo.setSort(sort);
    productListSearchParamPo.setPageSize(200);
    productListSearchParamPo.setParentStockInIdInList(
      pageResult
        .getRecords()
        .stream()
        .map(StockInFinishedProductItemVo::getId)
        .collect(Collectors.toList())
    );

    Map<String, Page<StockInProductItemVoPages>> productListMaps =
      stockInProductService.pagesByParentStockInId(productListSearchParamPo);

    for (StockInFinishedProductItemVo itemVo : pageResult.getRecords()) {
      JSONObject itemJson = (JSONObject) JSONObject.toJSON(itemVo);
      itemJson.put(
        "productList",
        productListMaps.get(itemVo.getId().toString())
      );
      withChildPage.getRecords().add(itemJson);
    }
    return withChildPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 成品入库单分页查询结果
   */
  @Override
  public Page<?> pageWithChildSearch(
    StockInFinishedProductSearchParamPo search
  ) {
    return appendWithChild(
      pageSearch(search),
      search.toChildSort("productList")
    );
  }

  /**
   * 仅获取子表的查询结果
   * @param parentId 主表编号
   * @param search 查询条件(仅使用分页参数，不处理其它条件)
   * @return
   */
  @Override
  public Page<?> pageOnlyChildSearch(
    Long parentId,
    StockInFinishedProductSearchParamPo search
  ) {
    StockInFinishedProductSearchParamPo parentSearchParam =
      new StockInFinishedProductSearchParamPo();
    parentSearchParam.setIdEq(parentId);
    List<StockInFinishedProductItemVo> parentList = search(parentSearchParam);
    if (parentList.size() > 0) {
      StockInFinishedProductItemVo itemVo = parentList.get(0);

      StockInProductSearchParamPo productListSearchParamPo =
        new StockInProductSearchParamPo();
      productListSearchParamPo.setPageSize(search.getPageSize());
      productListSearchParamPo.setCurrent(search.getCurrent());
      productListSearchParamPo.setParentStockInId(itemVo.getId());
      return stockInProductService.pageSearch(productListSearchParamPo);
    } else {
      return null;
    }
  }

  /**
   * 成品入库单快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'StockInFinishedProductOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<StockInFinishedProductItemVo>> searchOptions(
    StockInFinishedProductSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询成品入库单
   * @param search 查询条件
   * @return 成品入库单列表查询结果
   */
  @Override
  public List<StockInFinishedProductItemVo> search(
    StockInFinishedProductSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询成品入库单最后更新时间
   * @param search 查询条件
   * @return 成品入库单最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(StockInFinishedProductSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 返回满足搜索条件的统计信息
   * @param search 搜索参数
   */
  @Override
  public Map<String, Object> searchForStatistical(
    StockInFinishedProductSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchForStatistical(search);
  }

  /**
   * 推送领星
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了推送领星操作"
  )
  @Override
  public void pushLingXing(Long id) throws Exception {
    if (stockInFinishedProductPushLingXingAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockInFinishedProductPushLingXingAction.run(id);
  }

  /**
   * 打印入库单（模版）
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了打印入库单（模版）操作"
  )
  @Override
  public void printReceiptTemplates(Long id) throws Exception {
    if (stockInFinishedProductPrintReceiptTemplatesAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockInFinishedProductPrintReceiptTemplatesAction.run(id);
  }

  /**
   * 打印产品条码（自定义）
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了打印产品条码（自定义）操作"
  )
  @Override
  public void printProductBarCodeCustoms(Long id) throws Exception {
    if (stockInFinishedProductPrintProductBarCodeCustomsAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockInFinishedProductPrintProductBarCodeCustomsAction.run(id);
  }

  /**
   * 打印产品条码（模版）
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了打印产品条码（模版）操作"
  )
  @Override
  public void printProductBarCodeTemplates(Long id) throws Exception {
    if (stockInFinishedProductPrintProductBarCodeTemplatesAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockInFinishedProductPrintProductBarCodeTemplatesAction.run(id);
  }

  /**
   * 打印FNSKU条码（自定义）
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了打印FNSKU条码（自定义）操作"
  )
  @Override
  public void printFNSKUBarcodeCustoms(Long id) throws Exception {
    if (stockInFinishedProductPrintFNSKUBarcodeCustomsAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockInFinishedProductPrintFNSKUBarcodeCustomsAction.run(id);
  }

  /**
   * 打印FNSKU条码（模版）
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了打印FNSKU条码（模版）操作"
  )
  @Override
  public void printFNSKUBarcodeTemplates(Long id) throws Exception {
    if (stockInFinishedProductPrintFNSKUBarcodeTemplatesAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockInFinishedProductPrintFNSKUBarcodeTemplatesAction.run(id);
  }

  /**
   * 提交
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了提交操作"
  )
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void custSubmitOrder(List<Long> ids) throws Exception {
    executeScriptEngine.callJsInResource(
      "scripts/StockInFinishedProduct_custSubmitOrder.js",
      ids,
      null,
      this
    );
  }

  /**
   * 批量审核
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了批量审核操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void applyInBatchStorage(List<Long> ids) throws Exception {
    List<Long> list = Convert.toList(Long.class, ids);
    for (Long id : list) {
      StockInFinishedProductVo vo = getVoById(id);
      InventoryStorageFormVo formVo = prepareApplyInBatchStorage(vo);
      inventoryBusinessService.storage(formVo);
      // 更新成功状态
      StockInFinishedProduct updateStatusEntity = new StockInFinishedProduct();
      updateStatusEntity.setId(id);
      updateStatusEntity.setStatus("1");
      updateById(updateStatusEntity);
    }
  }

  /**
   * 准备用于 批量审核 的参数
   */
  protected InventoryStorageFormVo prepareApplyInBatchStorage(
    StockInFinishedProductVo vo
  ) throws Exception {
    if (!"0".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryStorageFormVo formVo = new InventoryStorageFormVo();
    if (ReflectUtil.hasField(StockInFinishedProductVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setSupportNegative(true);
    formVo.setTo(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getOrderSn());
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWarehouse())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getWarehouse());
    for (StockInProductItemVo stockInProduct : vo.getProductList()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(stockInProduct.getProductId());
      InventoryStorageVo storageItem = new InventoryStorageVo();
      storageItem.setItem(inventoryItem);
      storageItem.setQty(
        String.valueOf(stockInProduct.getQuantity()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(stockInProduct.getQuantity())
      );
      storageItem.setAmount(stockInProduct.getSubtotal());
      storageItem.setCustomId(vo.getId());
      storageItem.setCustomBdId(stockInProduct.getId());
      formVo.add(storageItem);
    }
    return formVo;
  }

  /**
   * 批量下推应付单
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了批量下推应付单操作"
  )
  @Override
  public void batchPushPy(List<Long> ids) throws Exception {
    if (stockInFinishedProductBatchPushPyAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockInFinishedProductBatchPushPyAction.run(ids);
  }

  /**
   * 下推其他出库单
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了下推其他出库单操作"
  )
  @Override
  public void pushStockOther(Long id) throws Exception {
    if (stockInFinishedProductPushStockOtherAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockInFinishedProductPushStockOtherAction.run(id);
  }

  /**
   * 下推销售出库单
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了下推销售出库单操作"
  )
  @Override
  public void pushSellOrder(Long id) throws Exception {
    if (stockInFinishedProductPushSellOrderAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockInFinishedProductPushSellOrderAction.run(id);
  }

  /**
   * 审核
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了审核操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void applyInStorage(Long id) throws Exception {
    StockInFinishedProductVo vo = getVoById(id);
    InventoryStorageFormVo formVo = prepareApplyInStorage(vo);
    inventoryBusinessService.storage(formVo);
    // 更新成功状态
    StockInFinishedProduct updateStatusEntity = new StockInFinishedProduct();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("1");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 审核 的参数
   */
  protected InventoryStorageFormVo prepareApplyInStorage(
    StockInFinishedProductVo vo
  ) throws Exception {
    if (!"0".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryStorageFormVo formVo = new InventoryStorageFormVo();
    if (ReflectUtil.hasField(StockInFinishedProductVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setSupportNegative(true);
    formVo.setTo(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getOrderSn());
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWarehouse())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getWarehouse());
    for (StockInProductItemVo stockInProduct : vo.getProductList()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(stockInProduct.getProductId());
      InventoryStorageVo storageItem = new InventoryStorageVo();
      storageItem.setItem(inventoryItem);
      storageItem.setQty(
        String.valueOf(stockInProduct.getQuantity()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(stockInProduct.getQuantity())
      );
      storageItem.setAmount(stockInProduct.getSubtotal());
      storageItem.setCustomId(vo.getId());
      storageItem.setCustomBdId(stockInProduct.getId());
      formVo.add(storageItem);
    }
    return formVo;
  }

  /**
   * 同步领星入库单
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了同步领星入库单操作"
  )
  @Override
  public void syncWarehousingOrder() throws Exception {
    if (stockInFinishedProductSyncWarehousingOrderAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockInFinishedProductSyncWarehousingOrderAction.run();
  }

  /**
   * 取消审核
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了取消审核操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void cancelWarehousing(Long id) throws Exception {
    StockInFinishedProductVo vo = getVoById(id);
    InventoryStorageFormVo formVo = prepareCancelWarehousing(vo);
    inventoryBusinessService.storage(formVo);
    // 更新成功状态
    StockInFinishedProduct updateStatusEntity = new StockInFinishedProduct();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("0");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 取消审核 的参数
   */
  protected InventoryStorageFormVo prepareCancelWarehousing(
    StockInFinishedProductVo vo
  ) throws Exception {
    if (!"1".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryStorageFormVo formVo = new InventoryStorageFormVo();
    if (ReflectUtil.hasField(StockInFinishedProductVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setOperate("撤消入库");
    formVo.setReverseQtySign(true);
    formVo.setSupportNegative(true);
    formVo.setTo(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getOrderSn());
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWarehouse())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getWarehouse());
    for (StockInProductItemVo stockInProduct : vo.getProductList()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(stockInProduct.getProductId());
      InventoryStorageVo storageItem = new InventoryStorageVo();
      storageItem.setItem(inventoryItem);
      storageItem.setQty(
        String.valueOf(stockInProduct.getQuantity()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(stockInProduct.getQuantity())
      );
      storageItem.setCustomId(vo.getId());
      storageItem.setCustomBdId(stockInProduct.getId());
      formVo.add(storageItem);
    }
    return formVo;
  }

  /**
   * 下推应付单
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了下推应付单操作"
  )
  @Override
  public void pushPayable(Long id) throws Exception {
    if (stockInFinishedProductPushPayableAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockInFinishedProductPushPayableAction.run(id);
  }

  /**
   * 提交表单
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了提交表单操作"
  )
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void custSmtStockin(Long id) throws Exception {
    executeScriptEngine.callJsInResource(
      "scripts/StockInFinishedProduct_custSmtStockin.js",
      id,
      null,
      this
    );
  }

  /**
   * 全部
   */
  @Override
  public List<StockInFinishedProductItemVo> entire(
    StockInFinishedProductSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.entire(search);
  }

  /**
   * 全部分页
   */
  @Override
  public Page<StockInFinishedProductItemVo> entirePage(
    StockInFinishedProductSearchParamPo search
  ) {
    Page<StockInFinishedProductItemVo> entirePage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return entirePage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return entirePage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    entirePage =
      this.baseMapper.entirePage(
          search.toPage(this.baseMapper.entireCount(search)),
          search
        );
    List<Long> recordIds = entirePage
      .getRecords()
      .stream()
      .map(StockInFinishedProductItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return entirePage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return entirePage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    entirePage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return entirePage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 成品入库单分页查询结果
   */
  @Override
  public Page<?> entirePageWithChildSearch(
    StockInFinishedProductSearchParamPo search
  ) {
    return appendWithChild(
      entirePage(search),
      search.toChildSort("productList")
    );
  }

  /**
   * 查询全部最后更新时间
   * @param search 查询条件
   * @return 全部最后更新时间
   */
  @Override
  public Date entireLastUpdateTime(StockInFinishedProductSearchParamPo search) {
    return this.baseMapper.entireLastUpdateTime(search);
  }

  /**
   * 待提交
   */
  @Override
  public List<StockInFinishedProductItemVo> changesToBeCommitted(
    StockInFinishedProductSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.changesToBeCommitted(search);
  }

  /**
   * 待提交分页
   */
  @Override
  public Page<StockInFinishedProductItemVo> changesToBeCommittedPage(
    StockInFinishedProductSearchParamPo search
  ) {
    Page<StockInFinishedProductItemVo> changesToBeCommittedPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return changesToBeCommittedPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return changesToBeCommittedPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    changesToBeCommittedPage =
      this.baseMapper.changesToBeCommittedPage(
          search.toPage(this.baseMapper.changesToBeCommittedCount(search)),
          search
        );
    List<Long> recordIds = changesToBeCommittedPage
      .getRecords()
      .stream()
      .map(StockInFinishedProductItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return changesToBeCommittedPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return changesToBeCommittedPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    changesToBeCommittedPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return changesToBeCommittedPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 成品入库单分页查询结果
   */
  @Override
  public Page<?> changesToBeCommittedPageWithChildSearch(
    StockInFinishedProductSearchParamPo search
  ) {
    return appendWithChild(
      changesToBeCommittedPage(search),
      search.toChildSort("productList")
    );
  }

  /**
   * 查询待提交最后更新时间
   * @param search 查询条件
   * @return 待提交最后更新时间
   */
  @Override
  public Date changesToBeCommittedLastUpdateTime(
    StockInFinishedProductSearchParamPo search
  ) {
    return this.baseMapper.changesToBeCommittedLastUpdateTime(search);
  }

  /**
   * 待入库
   */
  @Override
  public List<StockInFinishedProductItemVo> stockPending(
    StockInFinishedProductSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.stockPending(search);
  }

  /**
   * 待入库分页
   */
  @Override
  public Page<StockInFinishedProductItemVo> stockPendingPage(
    StockInFinishedProductSearchParamPo search
  ) {
    Page<StockInFinishedProductItemVo> stockPendingPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return stockPendingPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return stockPendingPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    stockPendingPage =
      this.baseMapper.stockPendingPage(
          search.toPage(this.baseMapper.stockPendingCount(search)),
          search
        );
    List<Long> recordIds = stockPendingPage
      .getRecords()
      .stream()
      .map(StockInFinishedProductItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return stockPendingPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return stockPendingPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    stockPendingPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return stockPendingPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 成品入库单分页查询结果
   */
  @Override
  public Page<?> stockPendingPageWithChildSearch(
    StockInFinishedProductSearchParamPo search
  ) {
    return appendWithChild(
      stockPendingPage(search),
      search.toChildSort("productList")
    );
  }

  /**
   * 查询待入库最后更新时间
   * @param search 查询条件
   * @return 待入库最后更新时间
   */
  @Override
  public Date stockPendingLastUpdateTime(
    StockInFinishedProductSearchParamPo search
  ) {
    return this.baseMapper.stockPendingLastUpdateTime(search);
  }

  /**
   * 已完成
   */
  @Override
  public List<StockInFinishedProductItemVo> completed(
    StockInFinishedProductSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.completed(search);
  }

  /**
   * 已完成分页
   */
  @Override
  public Page<StockInFinishedProductItemVo> completedPage(
    StockInFinishedProductSearchParamPo search
  ) {
    Page<StockInFinishedProductItemVo> completedPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return completedPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return completedPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    completedPage =
      this.baseMapper.completedPage(
          search.toPage(this.baseMapper.completedCount(search)),
          search
        );
    List<Long> recordIds = completedPage
      .getRecords()
      .stream()
      .map(StockInFinishedProductItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return completedPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return completedPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    completedPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return completedPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 成品入库单分页查询结果
   */
  @Override
  public Page<?> completedPageWithChildSearch(
    StockInFinishedProductSearchParamPo search
  ) {
    return appendWithChild(
      completedPage(search),
      search.toChildSort("productList")
    );
  }

  /**
   * 查询已完成最后更新时间
   * @param search 查询条件
   * @return 已完成最后更新时间
   */
  @Override
  public Date completedLastUpdateTime(
    StockInFinishedProductSearchParamPo search
  ) {
    return this.baseMapper.completedLastUpdateTime(search);
  }

  /**
   * 已撤销
   */
  @Override
  public List<StockInFinishedProductItemVo> undone(
    StockInFinishedProductSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.undone(search);
  }

  /**
   * 已撤销分页
   */
  @Override
  public Page<StockInFinishedProductItemVo> undonePage(
    StockInFinishedProductSearchParamPo search
  ) {
    Page<StockInFinishedProductItemVo> undonePage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return undonePage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return undonePage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    undonePage =
      this.baseMapper.undonePage(
          search.toPage(this.baseMapper.undoneCount(search)),
          search
        );
    List<Long> recordIds = undonePage
      .getRecords()
      .stream()
      .map(StockInFinishedProductItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return undonePage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return undonePage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    undonePage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return undonePage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 成品入库单分页查询结果
   */
  @Override
  public Page<?> undonePageWithChildSearch(
    StockInFinishedProductSearchParamPo search
  ) {
    return appendWithChild(
      undonePage(search),
      search.toChildSort("productList")
    );
  }

  /**
   * 查询已撤销最后更新时间
   * @param search 查询条件
   * @return 已撤销最后更新时间
   */
  @Override
  public Date undoneLastUpdateTime(StockInFinishedProductSearchParamPo search) {
    return this.baseMapper.undoneLastUpdateTime(search);
  }

  /**
   * 已驳回
   */
  @Override
  public List<StockInFinishedProductItemVo> reject(
    StockInFinishedProductSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.reject(search);
  }

  /**
   * 已驳回分页
   */
  @Override
  public Page<StockInFinishedProductItemVo> rejectPage(
    StockInFinishedProductSearchParamPo search
  ) {
    Page<StockInFinishedProductItemVo> rejectPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return rejectPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return rejectPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    rejectPage =
      this.baseMapper.rejectPage(
          search.toPage(this.baseMapper.rejectCount(search)),
          search
        );
    List<Long> recordIds = rejectPage
      .getRecords()
      .stream()
      .map(StockInFinishedProductItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return rejectPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return rejectPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    rejectPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return rejectPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 成品入库单分页查询结果
   */
  @Override
  public Page<?> rejectPageWithChildSearch(
    StockInFinishedProductSearchParamPo search
  ) {
    return appendWithChild(
      rejectPage(search),
      search.toChildSort("productList")
    );
  }

  /**
   * 查询已驳回最后更新时间
   * @param search 查询条件
   * @return 已驳回最后更新时间
   */
  @Override
  public Date rejectLastUpdateTime(StockInFinishedProductSearchParamPo search) {
    return this.baseMapper.rejectLastUpdateTime(search);
  }
}
